import { getApi } from '@/requestConfig';
import { authorizeRenewOSS } from '@/services/api/api-aliyun';
import { getToken } from '@/utils/token';
import { InboxOutlined } from '@ant-design/icons';
import OSS from 'ali-oss';
import { message, Upload } from 'antd';
import { UploadChangeParam, UploadFile } from 'antd/es/upload/interface';
import moment from 'moment';
import { useState } from 'react';
import { useModel } from 'umi';

interface UploadDraggerProps {
  value?: UploadFile[];
  onChange?(value: UploadFile[]): void;
  onPreview(file: UploadFile | undefined): void;
}

const UploadDragger: React.FC<UploadDraggerProps> = ({ value, onChange, onPreview }) => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const [preview, setPreviewState] = useState<UploadFile>();

  const customRequest = async (options: any) => {
    const isLt5GB = options.file.size / 1024 / 1024 / 1024 < 5;

    if (!isLt5GB) {
      message.error('文件大小不超过 5 GB');
      options.onError('文件大小不超过 5 GB', options.file);
      return;
    }

    const response = await authorizeRenewOSS({});

    if (response.code === 0) {
      const headers = {
        'Content-Disposition': 'attachment;',
      };

      const multipartUploadOptions = {
        callback: {
          url: `${getApi()}/publicity/record/attachment/save`,
          body: response.data.callbackBody,
          contentType: response.data.callbackContentType,
          satoken: getToken(),
        },
        progress: (p: number, cpt: any, res: any) => {
          options.onProgress({ percent: Math.round(p * 100).toFixed(2) }, options.file);
        },
        headers,
      };

      const OSSData = {
        accessKeyId: response.data.accessKeyId,
        accessKeySecret: response.data.accessKeySecret,
        stsToken: response.data.securityToken,
        region: response.data.callbackRegion,
        bucket: response.data.callbackBucket,
      };

      const client = new OSS({
        region: OSSData.region,
        accessKeyId: OSSData.accessKeyId,
        accessKeySecret: OSSData.accessKeySecret,
        stsToken: OSSData.stsToken,
        refreshSTSToken: async () => {
          const response = await authorizeRenewOSS({
            type: '20',
          });
          return {
            accessKeyId: response.data.accessKeyId,
            accessKeySecret: response.data.accessKeySecret,
            stsToken: response.data.securityToken,
          };
        },
        refreshSTSTokenInterval: 300000,
        bucket: OSSData.bucket,
      });

      client
        .multipartUpload(
          `${initialState?.currentUser?.organizationName}/image/${moment().format('yyyy-MM-DD')}/${
            options.file.name
          }`,
          options.file,
          multipartUploadOptions,
        )
        .then((response: any) => {
          if (response.data.code === 0) {
            options.onSuccess(response.data, options.file);
          } else {
            options.onError(response.data.msg, options.file);
          }
        })
        .catch((e: any) => {
          options.onError('发生错误', options.file);
        });
    }
  };

  const handlePreview = async (file: UploadFile) => {
    // onLoading(true);
    if (file?.status === 'done' && file.response && file.response?.data?.id) {
      onPreview(file);
      setPreviewState(file);
    } else {
      message.warning('暂无预览数据');
    }

    // setTimeout(() => {
    //   onLoading(false);
    // }, 180);
  };

  const handleChange = (info: UploadChangeParam) => {
    onChange(info.fileList);
  };

  const handleRemove = async (file: UploadFile) => {
    console.log('==============', file);

    // if (preview !== undefined && preview.uid === file.uid) {
    //   setPreviewState(undefined);
    // }
  };

  return (
    <Upload.Dragger
      listType="picture"
      multiple
      fileList={value}
      customRequest={customRequest}
      onPreview={handlePreview}
      onChange={handleChange}
      // onRemove={handleRemove}
    >
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">单击或拖动文件到该区域进行上传</p>
    </Upload.Dragger>
  );
};

export default UploadDragger;
